import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
import { usePinia } from "@/store/index";
import { logout } from "@/common";
const instance = axios.create({
  baseURL: "/api",
});
// 请求拦截器"
instance.interceptors.request.use(
  (config) => {
    // 携带请求头
    let token = localStorage.getItem("token");
    if (token) {
      if (config.headers) {
        config.headers["Authorization"] = token;
      }
    }
    return config;
  },
  (err) => Promise.reject(err)
);
// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const data = response.data as IResponse<any>;
    if (data.code === 401) {
      // token过期
      // 需要重新登录
      logout(undefined,() => {
        ElMessage.error("登录已过期,请重新登录");
      });
    } else if (data.code !== 200) {
      ElMessage.error(data.message);
    }
    return response.data;
  },
  (err) => {
    ElMessage.error("请求失败,错误信息" + err.message);
    Promise.reject(err);
  }
);

export default instance;
